<template>
  <goods-swipe :banners="info.pictures"></goods-swipe>
  <view class="goods-info mt-6px">
    <view class="goods-name flex-1 mb-20px leading-none">
      {{ info.name }}
    </view>
    <view class="flex items-center justify-between leading-none goods-price">
      <view class="flex items-end price">
        <image class="mr-8px oreo" :src="ossImg('others/goods/oreo.png')" />
        {{ info.score }}小饼干
      </view>
      <view class="goods-share flex items-center" @click.stop="shareClick">
        <image class="mr-8px" :src="ossImg('others/goods/share.png')" />
        <view>分享</view>
      </view>
    </view>
  </view>
  <view class="my-2">
    <oreo-cell
      :label="currentSku.label ? skuLabel : '选择数量规格'"
      :label-style="{ color: '#0D0D0D', fontSize: '16px' }"
      @click="
        skuVisible = true;
        chooseType = 1;
      "
    />
  </view>
  <view class="goods-content" v-html="info.intro"></view>
  <!-- footer action -->
  <view class="goods-action">
    <view class="flex-1 flex items-center px-12px" style="height: 100%">
      <view class="text-center leading-none" style="height: 100%">
        <button open-type="contact" class="kfbtn" @click.stop="toKefu">
          <view class="w-20px h-20px kfimg">
            <image :src="ossImg('others/goods/lxkf.png')" />
          </view>
          <view class="text-xxs" style="color: #8c8c8c">联系客服</view>
        </button>
      </view>
    </view>
    <button
      class="flex-1 flex items-center justify-center exchange"
      @click.stop="onExchange"
    >
      <image
        class="w-20px h-20px mr-8px"
        :src="ossImg('others/goods/gwc.png')"
      />
      <text>立即兑换</text>
    </button>
  </view>
  <!-- 商品分享 -->
  <oreo-popup round :show="shareVisible" position="bottom">
    <goods-share @poster="handleCreatePoster" @close="shareVisible = false" />
  </oreo-popup>
  <!-- SKU选择 -->
  <oreo-popup round :show="skuVisible" position="bottom">
    <biscuit-product-sku
      v-if="skuVisible"
      v-model:value="currentSku"
      :product="info"
      :choose-type="chooseType"
      @confirm="handleChooseSku"
      @close="skuVisible = false"
    />
  </oreo-popup>
  <!--  海报绘制  -->
  <poster ref="posterRef" :info="info" />
 
   
</template>

<script setup>
import GoodsSwipe from "@/components/goods-swipe";
import OreoCell from "@/components/oreo-cell";
import BiscuitProductSku from "@/components/biscuit-product-sku";
import GoodsShare from "@/components/goods-share";
import { computed, reactive, ref } from "vue";
import { GetGoodsDetail } from "@/services/mall";
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import { ossImg } from "@/utils/utils";
import Poster from "@/components/poster";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";

const posterRef = ref(null);
const chooseType = ref(1);
const shareVisible = ref(false);
const skuVisible = ref(false);
const currentSku = ref({
  label: "",
  quantity: 1,
  productSkuId: "",
});
const info = reactive({
  name: "",
  pictures: [],
  productSkus: [],
});

onLoad((option) => {
  getDetail(option.id);
  getApp().accessLogAdd();
  //#ifdef MP-WEIXIN
  wx.showShareMenu({
    withShareTicket: true,
    menus: ["shareAppMessage", "shareTimeline"],
  });
  //#endif
});

onShow(() => {
  // 用户进入时间
  enterTime = new Date();
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;

  getApp().emdlz(
    "track",
    "event",
    "points_store_page",
    "view",
    `product_detail_page_${info.id}`,
    stayTime
  );
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;
  getApp().emdlz(
    "track",
    "event",
    "points_store_page",
    "view",
    `product_detail_page_${info.id}`,
    stayTime
  );
});

onShareAppMessage((e) => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const pageUrl = currentPage + "?id=" + info.id;

  const shareObj = {
    title: "奥利奥玩心小宇宙商城", // 默认是小程序的名称(可以写slogan等)
    path: "", // 默认是当前页面，必须是以‘/’开头的完整路径
    imageUrl: info.imageUrl, //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    success: (res) => {
      // 转发成功之后的回调
      if (res.errMsg == "shareAppMessage:ok") {
      }
    },
    fail: (err) => {
      // 转发失败之后的回调
      console.log("转发失败之后的回调", err);
      if (res.errMsg == "shareAppMessage:fail cancel") {
        // 用户取消转发
        console.log("用户取消转发");
      } else if (res.errMsg == "shareAppMessage:fail") {
        // 转发失败，其中 detail message 为详细失败信息
        console.log("转发失败，其中detail message 为详细失败信息");
      }
    },
    complete: () => {
      // 转发结束之后的回调（转发成不成功都会执行）
      console.log("转发结束之后的回调（转发成不成功都会执行）");
    },
  };
  console.log(shareObj);
  return shareObj;
});

const skuLabel = computed(() => {
  const { label, quantity } = currentSku.value;
  return `${label} *${quantity}件`;
});

const shareClick = () => {
  getApp().emdlz(
    "track",
    "event",
    "points_store_page",
    "click",
    "share_buttom",
    ""
  );
  shareVisible.value = true;
};

// 底部立即兑换
const onExchange = () => {
  chooseType.value = 2;
  const { productSkuId, quantity, label } = currentSku.value;
  getApp().emdlz(
    "track",
    "event",
    "points_store_page",
    "click",
    `exchange1_${info.id}`,
    ""
  );
  if (label) {
    skuVisible.value = false;
    uni.navigateTo({
      url: `/personalPages/biscuit/order?productSkuId=${productSkuId}&quantity=${quantity}`,
    });
    return;
  }
  skuVisible.value = true;
};

const handleChooseSku = (sku) => {
  const { productSkuId, quantity } = sku;

  getApp().emdlz(
    "track",
    "event",
    "points_store_page",
    "click",
    `exchange2_${productSkuId}`,
    ""
  );
  skuVisible.value = false;
  currentSku.value = sku;
  if (chooseType.value === 2) {
    uni.navigateTo({
      url: `/personalPages/biscuit/order?productSkuId=${productSkuId}&quantity=${quantity}`,
    });
  }
};

const getDetail = async (id) => {
  const { data } = await GetGoodsDetail(id);
  Object.assign(info, data);
};

const toKefu = () => {
  getApp().emdlz("track", "event", "homepage", "click", "customer_service", "");
  getApp().sr().track("start_consult", {
    action_type: "consult_online",
    // more...
  });
};

const handleCreatePoster = () => {
  shareVisible.value = false;
  posterRef.value.createPoster(info, posterRef);
};
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";

.goods-content {
  padding-bottom: 50px;
  background-color: #f5f8fd;

  image,
  img {
    max-width: 100%;
  }
}

.goods-action {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: white;
  position: fixed;
  bottom: 0;
  left: 0;

  .exchange {
    height: inherit;
    background-color: #0058c6;
    color: white;
    font-size: 18px;
    border-radius: 0;
  }

  .kfbtn {
    padding: 0px;
    background-color: #fff;

    image {
      width: 100%;
      height: 100%;
      vertical-align: top;
    }

    .kfimg {
      margin: 0 auto;
      margin-top: 10px;
    }
  }

  .kfbtn::after {
    border: 0px !important;
  }
}

.goods-info {
  background: white;
  padding: 16px 14px;
  box-sizing: border-box;

  .goods-name {
    font-size: 18px;
    font-weight: 400;
    color: #0d0d0d;
    padding-right: 10px;
    line-height: 24px;
  }

  .goods-divider {
    width: 1px;
    height: 17px;
    background: #ebebeb;
  }

  .goods-share {
    white-space: nowrap;
    color: #818181;
    font-size: 12px;
    padding-left: 16px;
  }

  .goods-price {
    color: @primary-color;
    font-size: 18px;

    .price {
      &::before {
        content: "";
      }

      label {
        text-decoration: line-through;
        opacity: 0.51;
        margin-left: 11px;
      }
    }

    label {
      font-size: 12px;
    }
  }

  image {
    width: 16px;
    height: 16px;
    display: block;

    &.oreo {
      width: 17px;
      height: 20px;
    }
  }
}
</style>
